<template>
  <div>
    <ComDialog
      :width="'800'"
      @EventClose="closeFn"
      :dialogVisible="dialogVisible"
      title="新增题目"
    >
      <el-form
        :model="Formdata"
        :rules="rules"
        ref="Formdata"
        label-width="100px"
        class="demo-Formdata"
      >
        <!-- 选项 -->
        <el-form-item label="题目" prop="question">
          <el-input v-model="Formdata.question"></el-input>
        </el-form-item>
        <el-form-item label="选项">
          <div class="optionRow" v-for="(item, index) in arr" :key="index">
            <span> {{ item.label }}</span>
            <!-- 动态绑定属性 -->
            <el-input v-model="Formdata['option' + item.label]"> </el-input>
            <el-button
              class="delete-button"
              type="danger"
              icon="el-icon-delete"
              @click="subrowFn(index)"
              circle
              >-</el-button
            >
          </div>
        </el-form-item>
        <el-form-item label="答案" prop="selecedtArr">
          <el-checkbox-group
            ref="group"
            @change="checkboxChangeFn"
            v-model="Formdata.selecedtArr"
          >
            <el-checkbox
              v-for="item in arr"
              :key="item.label"
              :label="item.value"
              name="type"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group @change="selectTypeFn" v-model="Formdata.type">
            <el-radio label="1">必考</el-radio>
            <el-radio label="2">非必考</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="档案解析" prop="analysis">
          <el-input type="textarea" v-model="Formdata.analysis"></el-input>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button @click="addrowFn">新增一行</el-button>
        <el-button @click="closeFn">取消</el-button>
        <template v-if="editId">
          <el-button @click="editFn" v-hasPermi="['assess:examSubject:edit']"
            >修改</el-button
          >
        </template>
        <template v-else>
          <el-button @click="saveFn(0)" v-hasPermi="['assess:examSubject:add']"
            >保存并新增</el-button
          >
          <el-button
            type="primary"
            @click="saveFn(1)"
            v-hasPermi="['assess:examSubject:add', 'assess:examSubject:edit']"
            >保存</el-button
          ></template
        >
      </template>
    </ComDialog>
  </div>
</template>

<script>
import ComDialog from "../../../components/comDialog.vue";
import { getExamSubjectGetInfoApi } from "@/wss/api/HumanResources/EM/qustion.js";
export default {
  components: { ComDialog },
  props: {
    editId: {
      type: String,
      default: "",
    },
    dialogVisible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // 当前选择数字数组
      answerArr: [2],
      a: "",
      Formdata: {
        postionType: "",
        type: "",
        pattern: "",
        // 题目
        question: "",
        // 答案
        answer: 0,
        optionA: "",
        optionB: "",
        optionC: "",
        optionD: "",
        optionE: "",
        // 解析
        analysis: "",
        // 状态 0 已发布 1 草稿
        status: "",
        selecedtArr: [2],
      },
      // 类型数组
      typeArr: [],
      // 已选数组

      // 初始化数组
      arr: [{ label: "A", value: 2 }],
      // 最大限度选择的数组
      selectArr: [
        { label: "A", value: 2 },
        { label: "B", value: 4 },
        { label: "C", value: 8 },
        { label: "D", value: 16 },
        { label: "E", value: 32 },
      ],
      rules: {
        question: [
          {
            required: true,
            message: "请至少选择一个答案",
            trigger: "blur",
          },
        ],
        selecedtArr: [
          {
            required: true,
            message: "请选择答案",
            trigger: ["change"],
          },
        ],
        type: [
          {
            required: true,
            message: "请至少选择一个类型",
            trigger: ["change"],
          },
        ],
        analysis: [{ required: true, message: "请填写解析", trigger: "blur" }],
      },
    };
  },
  created() {
    // 回显
    if (this.editId) {
      this.getExamSubjectGetInfoFn();
    }
  },
  methods: {
    // 修改
    editFn() {
      this.answerAcmlnFn();
      console.log(this.Formdata, "formdata");

      this.$emit("EditEvent", this.Formdata);
      this.closeFn();
    },
    // 根据id查询
    async getExamSubjectGetInfoFn() {
      let { data, code } = await getExamSubjectGetInfoApi({ id: this.editId });
      console.log(data);
      if (code === 200) {
        this.Formdata = data;

        this.Formdata.selecedtArr ||= []; // this.Formdata.selecedtArr ||this.Formdata.selecedtArr=[]
        // 触发化数组编程空
        this.arr = [];
        let testarr = [];

        this.answerArr = [];
        //
        this.selectArr.forEach((item, index) => {
          //optionA……等于空吗？
          if (data["option" + item.label] != "") {
            this.arr.push(item);
            this.answerArr.push(item.value);
            testarr.push(item.value);
            this.a = Math.random();
          }
        });
        console.log(this.answerArr, "五环");
        console.log(this.Formdata, "formdata");

        this.Formdata.selecedtArr = testarr;
        // 后端要idstr
        this.Formdata.id = this.Formdata.idStr;
        // vue响应问题
        this.Formdata = JSON.parse(JSON.stringify(this.Formdata));
      }

      // console.log(result);
    },
    // 自定义验证规则
    // checkAnswer(rule, value, callback) {
    //   this.$nextTick(() => {
    //     if (this.Formdata.answer === 0) {
    //       callback(new Error("请输入题目内容"));
    //     } else {
    //       callback();
    //     }
    //   });
    //   // console.log(, "yanzhengguize");
    // },
    selectTypeFn(type) {
      this.Formdata.type = type;
    },
    //     answer累加
    answerAcmlnFn() {
      // a=2 b=4 c=8 d=16 e=32 后端需要把他们累加起来
      this.Formdata.answer = this.answerArr.reduce((current, add) => {
        return (current += add);
      }, 0);
    },

    // 新增
    saveFn(status) {
      this.$refs.Formdata.validate((isPass) => {
        if (isPass) {
          this.Formdata.status = status;
          this.answerAcmlnFn();
          this.$emit("submitEvent", this.Formdata);
        } else {
          this.$message({
            type: "warning",
            message: "请填写完成",
          });
        }
      });
    },
    test(a) {
      console.log("");
    },
    // 复选框发生改变
    checkboxChangeFn(valuearr, test) {
      // 没勾选的就不发给服务器
      this.selectArr.forEach((item) => {
        if (!valuearr.includes(item.value)) {
          this.Formdata["option" + item.label] = "";
        }
      });

      console.log(this.Formdata);

      this.answerArr = valuearr;
    },
    // 添加行
    addrowFn() {
      // 最多只可以添加5个
      if (this.arr.length == 5) {
        this.$message({
          type: "warning",
          message: "最多5个",
        });
        return;
      }

      let newarr = [];
      this.arr.forEach((item) => {
        newarr.push(item.label);
      });

      let curentValue = this.selectArr.find((item, index) => {
        // 是否包含，没有就添加
        if (!newarr.includes(item.label)) {
          return item;
        }
      });
      this.arr.push(curentValue);

      this.Formdata.selecedtArr.push(curentValue.value);
      this.answerArr.push(curentValue.value);
      // 排序
      this.arr.sort((a, b) => a.value - b.value);
      // console.log(this.answerArr);
    },
    // 减去行
    subrowFn(index) {
      if (this.arr.length == 1) {
        this.$message({
          type: "warning",
          message: "必须保留一个哦",
        });
        return;
      }

      let attr = this.arr.splice(index, 1);
      // this.Formdata.selecedtArr.findIndex((item) => {
      //   console.log(item);
      // });
      console.log(attr);
      let i = this.answerArr.findIndex((it) => {
        return it == attr[0].value;
      });
      // 删除时把answerArr中对应a……选项值也干掉
      this.answerArr.splice(i, 1);
      console.log(this.answerArr);
      this.Formdata["option" + attr[0].label] = null;
    },

    // 关闭弹窗
    closeFn() {
      this.Formdata = {
        postionType: "",
        type: "",
        pattern: "",
        // 题目
        question: "",
        // 答案
        answer: 0,
        optionA: "",
        optionB: "",
        optionC: "",
        optionD: "",
        optionE: "",
        // 解析
        analysis: "",
        // 状态 0 已发布 1 草稿
        status: "",
        selecedtArr: [],
      };
      this.$refs.Formdata.resetFields();
      // 清空编辑的id
      this.$emit("update:editId", "");
      this.$emit("update:dialogVisible", false);
    },
  },
};
</script>

<style lang="scss" scoped>
.optionRow {
  display: flex;
  margin: 10px 0px;
}
.delete-button {
  margin-left: 10px;
}
</style>